﻿Imports System.Net.Sockets
Imports System.Net
Imports RFDeviceNet

Public Class PacketWorker
    Implements IDisposable

    Private Shared _soc As Socket
    Private Shared _localIpe As IPEndPoint
    Private Shared _connection As ConnectionInfo

    Public Sub New()
        _connection = New ConnectionInfo()
        _soc = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
        _soc.ReceiveTimeout = 3000
        _localIpe = New IPEndPoint(IPAddress.Any, 6001)
        _soc.Bind(_localIpe)
    End Sub

    Public Function GetUdpPcketFrom620() As _UDP_DEVINFOBLOCK_PC_Net
        Dim count = _soc.Receive(_connection.Buffer)
        Dim mas = New Byte(count - 1) {}
        Buffer.BlockCopy(_connection.Buffer, 0, mas, 0, count)
        Dim block = GetBlock(mas)
        Return block
    End Function

    Private Shared Function GetBlock(mas As Byte()) As _UDP_DEVINFOBLOCK_PC_Net
        If mas.Length <> 268 Then
            Throw New Exception("wrong packet length")
        End If
        Dim block = New _UDP_DEVINFOBLOCK_PC_Net()
        Dim devTypeBuf = New Byte(1) {}
        Buffer.BlockCopy(mas, 0, devTypeBuf, 0, 2)
        block.DeviceType = BitConverter.ToUInt16(devTypeBuf, 0)
        Buffer.BlockCopy(mas, 2, block.IP, 0, 4)
        Buffer.BlockCopy(mas, 6, block.MAC, 0, 4)
        Buffer.BlockCopy(mas, 10, block.Info, 0, 256)
        Return block
    End Function

    Private Class ConnectionInfo
        Public Sub New()
            Buffer = New Byte(999) {}
        End Sub

        Public Property Buffer() As [Byte]()
            Get
                Return _mBuffer
            End Get
            Set(value As [Byte]())
                _mBuffer = value
            End Set
        End Property
        Private _mBuffer As [Byte]()
    End Class


    Public Sub IDisposable_Dispose() Implements IDisposable.Dispose
        _soc.Disconnect(True)
        _soc.Shutdown(SocketShutdown.Both)
        _soc.Close()
    End Sub
End Class
